package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
@Api("菜品分类接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //    分页查询
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页查询数据",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    }
    )
    public R<IPage> iPageR(Integer page, Integer pageSize, String name) {
//        分页构造器
        IPage<DishDto> page1 = new Page<>(page, pageSize);
        IPage<Dish> page2 = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
//        执行分页查询
        dishService.page(page2, lqw);
        BeanUtils.copyProperties(page2, page1, "records");
        List<Dish> records = page2.getRecords();
        List<DishDto> collect = records.stream().map(itrm -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(itrm, dishDto);
//            根据id查询分类
            Long categoryId = itrm.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if (byId != null) {
                String name1 = byId.getName();
                dishDto.setCategoryName(name1);
            }
            return dishDto;

        }).collect(Collectors.toList());
        page1.setRecords(collect);

        return R.success(page1);
    }

    //    菜品添加
    @PostMapping
    @ApiOperation("菜品添加")
    public R<String> update(@RequestBody DishDto dish) {
        log.info("新增菜品：{}", dish);
        dishService.saveFlavor(dish);
//        清理缓存
        String key="dish_"+dish.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    //    删除
    @DeleteMapping
    @ApiOperation("删除")
    public R<String> delete(@RequestParam List<Long> ids) {
        if (ids != null) {
            for (Long id : ids) {
                dishService.removeById(id);
//                清理缓存
                return R.success("删除成功");
            }
        }
        return R.error("删除失败");
    }

    //    修改回显
    @GetMapping("/{id}")
    @ApiOperation("修改回显")
    public R<DishDto> update(@PathVariable Long id) {
        DishDto dishDto = dishService.updatewhithFlavor(id);
        return R.success(dishDto);
    }

    //    修改
    @PutMapping
    @ApiOperation("修改")
    public R<String> updateFlavor(@RequestBody DishDto dishDto) {
        dishService.updatewhith(dishDto);
//        清理缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    //    停售
    @PostMapping("/status/{status}")
    public R<Dish> updatePost(@PathVariable Integer status, @RequestParam("ids") List<Long> ids) {
        log.info("{}", status);
        Dish byId = null;
        for (Long aLong : ids) {
            byId = dishService.getById(aLong);
            byId.setStatus(status);
            dishService.updateById(byId);
        }
        return R.success(byId);

    }

    //    添加菜品查询
//    @GetMapping("/list")
//    public R<List<Dish>> saveById(Dish dish) {
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Dish::getCategoryId, dish.getCategoryId());
//        lqw.eq(Dish::getStatus, 1);
//        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> list = dishService.list(lqw);
//        return R.success(list);
//    }
//    添加菜品
    @GetMapping("/list")
    public R<List<DishDto>> saveById(Dish dish) {
        List<DishDto> list1=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();//动态获取key值
        list1 = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(list1!=null){
            return R.success(list1);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, dish.getCategoryId());
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lqw);

         list1 = list.stream().map((item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            String name = byId.getName();
            dishDto.setCategoryName(name);

            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list2 = dishFlavorService.list(lqw1);
            dishDto.setFlavors((ArrayList<DishFlavor>) list2);
            return dishDto;
        })).collect(Collectors.toList());
//         查询数据库存入Redis中
        redisTemplate.opsForValue().set(key,list1,60, TimeUnit.MINUTES);
        return R.success(list1);
    }
}
